package com.lemeng.controller;


import com.aliyun.oss.OSSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

@RestController
@RequestMapping("upload")
public class UploadController {


    @Autowired
    OSSClient ossClient;

    @RequestMapping("uploadLocal")
    public String uploadLocal(MultipartFile file, HttpServletRequest request) throws Exception {
        String realPath = request.getSession().getServletContext().getRealPath("/");

        String name = file.getOriginalFilename();

        name = UUID.randomUUID().toString() + name.substring(name.lastIndexOf("."));

        File desc = new File(realPath + "/img/" + name);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }

        file.transferTo(desc);

        return "http://localhost:9101/img/" + name;
    }

    @RequestMapping("uploadOss")
    public String uploadOss(MultipartFile file, HttpServletRequest request) throws Exception {


        String name = file.getOriginalFilename();

        name = UUID.randomUUID().toString() + name.substring(name.lastIndexOf("."));

        String bucketName = "lemeng-zc666";
        ossClient.putObject(bucketName, name, file.getInputStream());


        //https://lemeng-zc666.oss-cn-beijing.aliyuncs.com/test2.png
        System.out.println();
        return "https://"+bucketName+"."+ossClient.getEndpoint().getHost()+"/"+name;
    }
}